package com.example.temp.controller;

import com.example.temp.common.Result;
import com.example.temp.entity.ClassEntity;
import com.example.temp.entity.Question;
import com.example.temp.entity.Student;
import com.example.temp.mapper.ClassMapper;
import com.example.temp.mapper.QuestionCategoryMapper;
import com.example.temp.mapper.QuestionMapper;
import com.example.temp.mapper.ResultMapper;
import com.example.temp.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * 
 *
 * @author 
 * @since 2023-02-20
 */
@RestController
@RequestMapping("/question")
public class QuestionController {

    // 创建日志器
    private static final Logger logger = Logger.getLogger(QuestionController.class.getName());

    // 图片存储相关路径
    private static final String QUESTION_IMAGE_DIR = "images/questions/";
    private static final String QUESTION_IMAGE_URL_PREFIX = "/questionPictures/";
    private static String absoluteImagePath; // 存储绝对路径
    
    @PostConstruct
    public void init() {
        try {
            // 获取当前项目运行路径
            String currentPath = new File(".").getCanonicalPath();
            absoluteImagePath = currentPath + File.separator + QUESTION_IMAGE_DIR;
            
            // 创建图片目录
            File imageDir = new File(absoluteImagePath);
            if (!imageDir.exists()) {
                boolean created = imageDir.mkdirs();
                if (created) {
                    logger.info("创建图片目录成功: " + absoluteImagePath);
                } else {
                    logger.warning("创建图片目录失败: " + absoluteImagePath);
                }
            }
            
            logger.info("题目图片存储路径: " + absoluteImagePath);
            logger.info("题目图片URL前缀: " + QUESTION_IMAGE_URL_PREFIX);
        } catch (IOException e) {
            logger.severe("初始化图片路径失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    // 注意：图片存储目录初始化已移到@PostConstruct方法中
    // 此处不需要额外的初始化代码

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionCategoryMapper questionCategoryMapper;

    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ResultMapper resultMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 
    @PostMapping("/insert")
    public Result insertQuestion(
            @RequestParam("categoryId") Integer categoryId,
            @RequestParam("type") String type,
            @RequestParam("answerTime") Integer answerTime,
            @RequestParam("questionText") String questionText,
            @RequestParam("answer") String answer,
            @RequestParam(value = "TeacherID", required = true) String teacherId,
            @RequestParam("score") Integer score) { // 

        logger.info("接收到题目提交请求:");
        logger.info("题目类型: " + type);
        logger.info("答题时间: " + answerTime);
        logger.info("题目文本: " + questionText);
        logger.info("答案: " + answer);
        logger.info("教师ID: " + teacherId);
        logger.info("默认得分: " + score); 
        logger.info("题目分类: " + categoryId); 
        
        
        // 验证答题时间是否为正整数
        if (answerTime == null || answerTime < 1) {
            logger.warning("答题时间验证失败: " + answerTime);
            return Result.fail("答题时间必须是大于等于1的整数");
        }
    
       
        // 移除ID设置，使用数据库自动递增
        Question question = new Question();
        question.setType(type);
        question.setAnswerTime(answerTime);
        question.setQuestionText(questionText);
        question.setCategoryId(categoryId);
        question.setAnswer(answer);
        question.setTeacherId(teacherId); // 设置教师ID
        question.setScore(score); // 设置默认得分
    
        int result = questionMapper.insert(question);
        return Result.success(result);
    }

    // 获取所有题目类型
    @GetMapping("/acquireTypes")
    public Result acquireTypes() {
        //从questionCategory表中获取所有类型
        List<String> types = questionCategoryMapper.acquireTypes();
        return Result.success(types);
    }

    // 查询单个题目
    @GetMapping("/query")
    public Result queryQuestion(@RequestParam int id) {
        Question question = questionMapper.queryQuestion(id);
        return Result.success(question);
    }

    @PutMapping("/update")
    public Result updateQuestion(@ModelAttribute Question question) {
        try {
            // 查询原始题目信息，确保题目存在
            Question originalQuestion = questionMapper.queryQuestion(question.getId());
            if (originalQuestion == null) {
                return Result.fail("题目不存在");
            }
            
            // 2. 检查题目是否已经关联到试卷中
            List<Integer> idList = new ArrayList<>();
            idList.add(question.getId());
            List<com.example.temp.entity.Result> relatedResults = resultMapper.findByQuestionId(idList);
            if (relatedResults != null && !relatedResults.isEmpty()) {
                return Result.fail("该题目已经关联到试题中，请先删除相关试卷");
            }
            
            // 更新题目信息
            int result = questionMapper.update(question);
            logger.info("更新题目结果: " + result);
            
            return result == 1 ? Result.success(result) : Result.fail("更新失败");
        } catch (Exception e) {
            logger.severe("更新题目时发生错误: " + e.getMessage());
            return Result.fail("更新题目时发生错误: " + e.getMessage());
        }
    }


    @GetMapping("/list")
    public Result showPageQuestion(
            @RequestParam(value = "categoryId", required = false) Integer categoryId,
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @RequestParam(value = "teacherId", required = false) String teacherId) {
        
        // 记录接收到的参数
        logger.info("接收到请求参数: type=" + type + ", pageNum=" + pageNum + ", pageSize=" + pageSize + ", teacherId=" + teacherId + ", categoryId=" + categoryId);
        
        // 参数校验和安全处理
        if (pageNum < 1) {
            pageNum = 1;
        }
        
        if (pageSize < 1) {
            pageSize = 5;
        }
        
        // 准备查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("categoryId", categoryId);
        params.put("teacherId", teacherId);
        params.put("pageNum", (pageNum - 1) * pageSize);  // 转换为数据库LIMIT开始位置
        params.put("pageSize", pageSize);
        
        // 添加查询性能跟踪
        long startTime = System.currentTimeMillis();
        
        // 查询数据和总数
        List<Question> questions = questionMapper.search(params);
        int total = questionMapper.getTotal(params);
        
        // 计算查询耗时
        long queryTime = System.currentTimeMillis() - startTime;
        
        // 记录查询性能
        logger.info("查询题目列表完成，类型: " + type + ", 教师ID: " + teacherId + ", 页码: " + pageNum + ", 每页数量: " + pageSize + ", 总数: " + total + ", 耗时: " + queryTime + "ms");
        
        // 构建分页结果对象
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("items", questions);
        resultData.put("total", total);
        resultData.put("pageNum", pageNum);
        resultData.put("pageSize", pageSize);
        
        return Result.success(resultData);
    }

    // 批量删除题目
    @DeleteMapping("/batchDelete")
    public Result batchDeleteQuestions(@RequestBody List<String> questionIds, @RequestParam(required = false) String teacherId) {
        if (questionIds == null || questionIds.isEmpty()) {
            return Result.fail("没有选择题目");
        }
        
        // 将字符串ID列表转换为整数列表
        List<Integer> ids = questionIds.stream()
            .map(Integer::parseInt)
            .collect(Collectors.toList());
        
        // 如果是教师角色，检查所有题目是否都属于该教师
        if (teacherId != null && !teacherId.isEmpty()) {
            // 查询所有要删除的题目
            List<Question> questions = questionMapper.findByIds(ids);
            
            // 检查每个题目是否都属于该教师
            for (Question question : questions) {
                // 使用getTeacherId()方法获取教师ID (对应数据库中的TeacherID字段)
                if (!teacherId.equals(question.getTeacherId())) {
                    return Result.fail("您没有权限删除其他教师创建的题目");
                }
            }
        }
        
        // 执行删除操作
        int result = questionMapper.deleteByIds(ids);

        if (result > 0) {
            return Result.success(result);  // 
        } else {
            return Result.fail("删除失败");
        }
    }

    /**
     * 发布试题到指定班级
     * 支持为每道题目设置不同分值
     */
    @PostMapping("/publish")
    public Result publishQuestions(@RequestBody Map<String, Object> params) {
        logger.info("发布试题请求参数: " + params);
        
        try {
            // 1. 提取基本参数
            List<Integer> questionIds = (List<Integer>) params.get("questionIds");
            Integer classId = (Integer) params.get("classId");
            String publishType = (String) params.get("publishType");
            Integer teacherId = (Integer) params.get("teacherId");
            Integer answerTime = (Integer) params.get("answerTime");
            String title = (String) params.get("title"); // 测试名称
            
            // 2. 获取题目分值信息
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> questionScores = (List<Map<String, Object>>) params.get("questionScores");
            Map<Integer, Integer> scoreMap = new HashMap<>();
            
            // 如果前端传了分值信息，则解析保存
            if (questionScores != null && !questionScores.isEmpty()) {
                for (Map<String, Object> item : questionScores) {
                    Integer questionId = (Integer) item.get("questionId");
                    Integer maxScore = (Integer) item.get("maxScore");
                    if (questionId != null && maxScore != null) {
                        scoreMap.put(questionId, maxScore);
                    }
                }
            }
            
            // 3. 解析时间参数
            final Timestamp startTime;
            final Timestamp endTime;
            if (params.get("startTime") != null) {
                String startTimeStr = params.get("startTime").toString();
                startTime = Timestamp.valueOf(startTimeStr.contains(":") ? 
                    (startTimeStr.contains(":00") ? startTimeStr : startTimeStr + ":00") : 
                    startTimeStr + " 00:00:00");
            } else {
                startTime = null;
            }
            if (params.get("endTime") != null) {
                String endTimeStr = params.get("endTime").toString();
                endTime = Timestamp.valueOf(endTimeStr.contains(":") ? 
                    (endTimeStr.contains(":00") ? endTimeStr : endTimeStr + ":00") : 
                    endTimeStr + " 00:00:00");
            } else {
                endTime = null;
            }
            
            // 4. 基本参数验证
            if (questionIds == null || questionIds.isEmpty()) {
                return Result.fail("未选择任何试题");
            }
            if (classId == null) {
                return Result.fail("未选择任何班级");
            }
            if (publishType == null || !Arrays.asList("课前", "课中", "课后", "测试").contains(publishType)) {
                return Result.fail("无效的发布类型");
            }
            if (teacherId == null) {
                return Result.fail("无法获取教师身份信息");
            }
            
            // 5. 验证班级归属
            ClassEntity classEntity = classMapper.findById(classId);
            if (classEntity == null || !teacherId.equals(classEntity.getTeacherID())) {
                return Result.fail("班级不存在或您没有权限操作该班级");
            }
            
            // 6. 获取班级学生
            List<Student> students = studentMapper.findByClassId(classId);
            if (students == null || students.isEmpty()) {
                return Result.success("该班级没有学生，无需发布");
            }
            
            // 7. 准备SQL语句，使用正确的数据库表列名
            // 根据数据库表结构：is_submit和is_correct是枚举类型，接受字符串'0'或'1'
            String sql = "INSERT INTO results (student_id, question_id, class_id, score, max_score, start_time, end_time, answer_time, purpose, is_submit, is_correct, comment) " +
                       "VALUES (?, ?, ?, 0, ?, ?, ?, ?, ?, '0', '0', ?)";
            
            int successCount = 0;
            int failCount = 0;
            List<Integer> createdResultIds = new ArrayList<>();
            
            // 8. 为每个学生创建题目记录
            for (Student student : students) {
                for (Integer questionId : questionIds) {
                    try {
                        // 检查题目是否存在
                        Question question = questionMapper.getByID(questionId);
                        if (question == null) {
                            logger.warning("题目不存在: " + questionId);
                            continue;
                        }
                        
                        // 获取该题目的分值，如果没有自定义分值则使用题目原始分值
                        Integer questionScore = question.getScore();
                        int maxScore = scoreMap.getOrDefault(questionId, (questionScore == null ? 5 : questionScore));
                        
                        // 使用KeyHolder获取生成的主键
                        KeyHolder keyHolder = new GeneratedKeyHolder();
                        jdbcTemplate.update(connection -> {
                            PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                            ps.setString(1, student.getStudentID());  // student_id
                            ps.setInt(2, questionId);                // question_id
                            ps.setInt(3, classId);                   // class_id
                            ps.setInt(4, maxScore);                  // max_score
                            ps.setTimestamp(5, startTime);           // start_time
                            ps.setTimestamp(6, endTime);             // end_time
                            ps.setInt(7, answerTime);                // answer_time
                            ps.setString(8, publishType);            // purpose
                            ps.setString(9, null);                   // comment字段用于保存老师评语，发布时为null
                            return ps;
                        }, keyHolder);
                        
                        // 获取生成的resultId
                        Number generatedKey = keyHolder.getKey();
                        if (generatedKey != null) {
                            createdResultIds.add(generatedKey.intValue());
                        }
                        
                        successCount++;
                    } catch (Exception e) {
                        failCount++;
                        logger.warning(String.format("创建记录失败 - 学生ID: %s, 题目ID: %d, 错误: %s", 
                            student.getStudentID(), questionId, e.getMessage()));
                    }
                }
            }
            
            // 判断返回结果，如果所有记录都失败则返回失败信息
            if (successCount > 0) {
                // 发布成功后，将数据保存到result_name表中
                try {
                    // 获取班级名称
                    String className = classEntity.getClassName();
                    
                    // 将createdResultIds转换为字符串，用逗号分隔
                    String resultIdStr = createdResultIds.stream()
                        .map(Object::toString)
                        .collect(Collectors.joining(","));
                    
                    // 使用title作为result_name，如果为空则使用默认值
                    String resultName = title != null && !title.trim().isEmpty() ? title : publishType + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                    
                    // 插入到result_name表
                    String resultnameSql = "INSERT INTO result_name (result_id, result_name, class_name) VALUES (?, ?, ?)"; 
                    jdbcTemplate.update(resultnameSql, resultIdStr, resultName, className);
                    logger.info("已将发布信息保存到result_name表: " + resultName);
                } catch (Exception e) {
                    logger.severe("保存到result_name表失败: " + e.getMessage());
                    String errorMsg = String.format("发布过程中保存result_name记录失败: %s", e.getMessage());
                    return Result.fail(errorMsg);
                }
                
                String resultMsg = String.format("试题发布成功: 成功创建%d条记录，失败%d条", successCount, failCount);
                logger.info(resultMsg);
                return Result.success(resultMsg);
            } else {
                String resultMsg = String.format("试题发布失败: 所有%d条记录创建失败", failCount);
                logger.warning(resultMsg);
                return Result.fail(resultMsg);
            }
        } catch (Exception e) {
            logger.severe("发布试题失败: " + e.getMessage());
            e.printStackTrace();
            return Result.fail("发布试题失败: " + e.getMessage());
        }
    }
    
    // 注意：由于表结构更新，不再需要生成publishId
    
    /**
     * 查询表结构（仅用于调试）
     */
    @GetMapping("/check-table-structure")
    public Result checkTableStructure() {
        try {
            // 获取results表结构
            List<Map<String, Object>> columns = jdbcTemplate.queryForList(
                "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_KEY " +
                "FROM INFORMATION_SCHEMA.COLUMNS " +
                "WHERE TABLE_SCHEMA = 'teaManageSystem' AND TABLE_NAME = 'results'");
            
            StringBuilder sb = new StringBuilder("results表结构\n");
            for (Map<String, Object> column : columns) {
                sb.append(column.get("COLUMN_NAME")).append(" - ");
                sb.append(column.get("DATA_TYPE")).append(" ");
                sb.append(column.get("COLUMN_KEY")).append("\n");
            }
            
            logger.info(sb.toString());
            return Result.success(columns);
        } catch (Exception e) {
            logger.severe("获取表结构失败: " + e.getMessage());
            return Result.fail("获取表结构失败: " + e.getMessage());
        }
    }
    
    /**
     * 解析时间字符串为Timestamp
     * @param dateString 时间字符串
     * @param formats 支持的时间格式数组
     * @return 解析后的Timestamp，解析失败返回null
     */
    private Timestamp parseTimestamp(String dateString, SimpleDateFormat[] formats) {
        if (dateString == null || dateString.isEmpty()) {
            return null;
        }
        
        // 移除可能的时区信息
        dateString = dateString.replace("Z", "").replace("T", " ").trim();
        
        // 尝试使用每种格式进行解析
        for (SimpleDateFormat format : formats) {
            try {
                Date date = format.parse(dateString);
                if (date != null) {
                    return new Timestamp(date.getTime());
                }
            } catch (ParseException e) {
                // 尝试下一种格式
                continue;
            }
        }
        
        // 如果所有格式都失败，尝试使用标准格式
        try {
            return Timestamp.valueOf(dateString);
        } catch (IllegalArgumentException e) {
            logger.warning("无法解析时间字符串: " + dateString);
            return null;
        }
    }
    
    /**
     * 删除测试（根据测试名称）
     * @param params 包含testName和teacherId
     * @return 结果信息
     */
    @PostMapping("/deleteTest")
    public Result deleteTest(@RequestBody Map<String, Object> params) {
        logger.info("收到删除测试请求，参数: " + params);
        
        // 获取并验证参数
        String testName = null;
        Integer teacherId = null;
        
        try {
            // 处理参数
            Object testNameObj = params.get("testName");
            if (testNameObj != null) {
                testName = testNameObj.toString();
            }
            
            Object teacherIdObj = params.get("teacherId");
            if (teacherIdObj != null) {
                teacherId = teacherIdObj instanceof Integer ? 
                    (Integer) teacherIdObj : Integer.valueOf(teacherIdObj.toString());
            }
        } catch (NumberFormatException e) {
            logger.warning("参数格式错误: " + e.getMessage());
            return Result.fail("参数格式错误，请输入有效的数字");
        }
        
        // 参数校验
        if (testName == null || testName.trim().isEmpty()) {
            return Result.fail("测试名称不能为空");
        }
        if (teacherId == null) {
            return Result.fail("教师ID不能为空");
        }
        
        try {
            // 1. 根据测试名称获取对应的resultIds
            String resultNameSql = "SELECT result_id FROM result_name WHERE result_name = ?";
            List<Map<String, Object>> resultNameRecords = jdbcTemplate.queryForList(resultNameSql, testName);
            
            if (resultNameRecords.isEmpty()) {
                return Result.fail("未找到指定的测试：" + testName);
            }
            
            String resultIds = (String) resultNameRecords.get(0).get("result_id");
            if (resultIds == null || resultIds.trim().isEmpty()) {
                return Result.fail("测试没有关联的答题记录");
            }
            
            // 2. 解析resultIds字符串
            String[] ids = resultIds.split(",");
            List<Integer> resultIdList = new ArrayList<>();
            for (String id : ids) {
                try {
                    resultIdList.add(Integer.parseInt(id.trim()));
                } catch (NumberFormatException e) {
                    logger.warning("无效的resultId: " + id);
                }
            }
            
            if (resultIdList.isEmpty()) {
                return Result.fail("没有有效的答题记录ID");
            }
            
            // 3. 删除所有相关的result记录
            int totalDeleted = 0;
            int successCount = 0;
            
            for (Integer resultId : resultIdList) {
                try {
                    String deleteResultSql = "DELETE FROM results WHERE id = ?";
                    int deleted = jdbcTemplate.update(deleteResultSql, resultId);
                    if (deleted > 0) {
                        successCount++;
                    }
                    totalDeleted++;
                } catch (Exception e) {
                    logger.warning("删除result记录失败，resultId: " + resultId + ", 错误: " + e.getMessage());
                }
            }
            
            // 4. 删除result_name记录
            int resultNameDeleted = 0;
            try {
                String deleteResultNameSql = "DELETE FROM result_name WHERE result_name = ?";
                resultNameDeleted = jdbcTemplate.update(deleteResultNameSql, testName);
            } catch (Exception e) {
                logger.warning("删除result_name记录失败，testName: " + testName + ", 错误: " + e.getMessage());
            }
            
            if (successCount > 0 && resultNameDeleted > 0) {
                // 记录日志
                logger.info(String.format("测试[%s]已由教师[%d]删除；成功删除%d/%d条result记录，1条result_name记录", 
                    testName, teacherId, successCount, totalDeleted));
                
                // 返回成功响应
                Map<String, Object> data = new HashMap<>();
                data.put("testName", testName);
                data.put("deletedResultRecords", successCount);
                data.put("totalResultRecords", totalDeleted);
                data.put("deletedResultNameRecords", resultNameDeleted);
                
                return Result.success(data);
            } else {
                logger.warning(String.format("删除测试失败：testName=%s, successCount=%d, resultNameDeleted=%d", 
                    testName, successCount, resultNameDeleted));
                return Result.fail("删除测试失败，请稍后重试");
            }
        } catch (Exception e) {
            logger.warning("删除测试异常: " + e.getMessage());
            return Result.fail("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 延长考试截止时间（根据测试名称）
     * @param params 包含testName, teacherId和延长的分钟数minutes
     * @return 结果信息
     */
    @PostMapping("/extendExamTime")
    public Result extendExamTime(@RequestBody Map<String, Object> params) {
        logger.info("收到延长考试时间请求，参数: " + params);
        
        // 获取并验证参数
        String testName = null;
        Integer teacherId = null;
        Integer minutes = null;
        
        try {
            // 处理参数
            Object testNameObj = params.get("testName");
            if (testNameObj != null) {
                testName = testNameObj.toString();
            }
            
            Object teacherIdObj = params.get("teacherId");
            if (teacherIdObj != null) {
                teacherId = teacherIdObj instanceof Integer ? 
                    (Integer) teacherIdObj : Integer.valueOf(teacherIdObj.toString());
            }
            
            Object minutesObj = params.get("minutes");
            if (minutesObj != null) {
                minutes = minutesObj instanceof Integer ? 
                    (Integer) minutesObj : Integer.valueOf(minutesObj.toString());
            }
        } catch (NumberFormatException e) {
            logger.warning("参数格式错误: " + e.getMessage());
            return Result.fail("参数格式错误，请输入有效的数字");
        }
        
        // 参数校验
        if (testName == null || testName.trim().isEmpty()) {
            return Result.fail("测试名称不能为空");
        }
        if (teacherId == null) {
            return Result.fail("教师ID不能为空");
        }
        if (minutes == null || minutes <= 0) {
            return Result.fail("延长时间必须大于0分钟");
        }
        
        try {
            // 1. 根据测试名称获取对应的resultIds
            String resultNameSql = "SELECT result_id FROM result_name WHERE result_name = ?";
            List<Map<String, Object>> resultNameRecords = jdbcTemplate.queryForList(resultNameSql, testName);
            
            if (resultNameRecords.isEmpty()) {
                return Result.fail("未找到指定的测试：" + testName);
            }
            
            String resultIds = (String) resultNameRecords.get(0).get("result_id");
            if (resultIds == null || resultIds.trim().isEmpty()) {
                return Result.fail("测试没有关联的答题记录");
            }
            
            // 2. 解析resultIds字符串
            String[] ids = resultIds.split(",");
            List<Integer> resultIdList = new ArrayList<>();
            for (String id : ids) {
                try {
                    resultIdList.add(Integer.parseInt(id.trim()));
                } catch (NumberFormatException e) {
                    logger.warning("无效的resultId: " + id);
                }
            }
            
            if (resultIdList.isEmpty()) {
                return Result.fail("没有有效的答题记录ID");
            }
            
            // 3. 获取当前考试信息（从第一个result记录获取基本信息）
            String firstResultSql = "SELECT * FROM results WHERE id = ? LIMIT 1";
            List<Map<String, Object>> firstResultList = jdbcTemplate.queryForList(firstResultSql, resultIdList.get(0));
            
            if (firstResultList.isEmpty()) {
                return Result.fail("未找到指定的考试信息");
            }
            
            Map<String, Object> firstResult = firstResultList.get(0);
            Timestamp currentEndTime = (Timestamp) firstResult.get("end_time");
            Integer currentAnswerTime = (Integer) firstResult.get("answer_time");
            
            if (currentEndTime == null) {
                return Result.fail("当前考试没有设置截止时间");
            }
            
            // 4. 计算新的截止时间和答题时间
            long newEndTimeMillis = currentEndTime.getTime() + (long) minutes * 60 * 1000;
            Timestamp newEndTime = new Timestamp(newEndTimeMillis);
            
            if (currentAnswerTime == null) {
                currentAnswerTime = 0; // 如果原答题时间为空，则默认为0
            }
            int newAnswerTime = currentAnswerTime + minutes * 60; // 转换为秒
            
            // 5. 更新所有相关的result记录
            int totalUpdated = 0;
            int successCount = 0;
            
            for (Integer resultId : resultIdList) {
                try {
                    // 更新end_time和answer_time
                    String updateSql = "UPDATE results SET end_time = ?, answer_time = ? WHERE id = ?";
                    int updated = jdbcTemplate.update(updateSql, newEndTime, newAnswerTime, resultId);
                    if (updated > 0) {
                        successCount++;
                    }
                    totalUpdated++;
                } catch (Exception e) {
                    logger.warning("更新result记录失败，resultId: " + resultId + ", 错误: " + e.getMessage());
                }
            }
            
            if (successCount > 0) {
                // 记录日志
                logger.info(String.format("测试[%s]的截止时间已由教师[%d]从[%s]延长到[%s]，延长了%d分钟；答题时间从%d秒更新为%d秒；成功更新%d/%d条记录", 
                    testName, teacherId, currentEndTime, newEndTime, minutes, currentAnswerTime, newAnswerTime, successCount, totalUpdated));
                
                // 返回成功响应
                Map<String, Object> data = new HashMap<>();
                data.put("testName", testName);
                data.put("newEndTime", newEndTime);
                data.put("extendedMinutes", minutes);
                data.put("newAnswerTime", newAnswerTime);
                data.put("updatedRecords", successCount);
                data.put("totalRecords", totalUpdated);
                
                return Result.success(data);
            } else {
                logger.warning(String.format("更新考试时间失败：testName=%s, successCount=%d, totalUpdated=%d", 
                    testName, successCount, totalUpdated));
                return Result.fail("更新考试时间失败，请稍后重试");
            }
        } catch (Exception e) {
            logger.warning("延长考试截止时间异常: " + e.getMessage());
            return Result.fail("系统异常：" + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteQuestion(@PathVariable Integer id) {
        try {
            // 1. 检查题目是否存在
            Question question = questionMapper.queryQuestion(id);
            if (question == null) {
                return Result.fail("题目不存在或已被删除");
            }
            
            // 2. 检查题目是否已经关联到试卷中
            List<Integer> idList = new ArrayList<>();
            idList.add(id);
            List<com.example.temp.entity.Result> relatedResults = resultMapper.findByQuestionId(idList);
            if (relatedResults != null && !relatedResults.isEmpty()) {
                return Result.fail("该题目已经关联到试题中，请先删除相关试卷");
            }
            
            // // 3. 删除题目图片文件（如果有）
            // if (question.getImageUrl() != null && !question.getImageUrl().isEmpty()) {
            //     try {
            //         String imagePath = question.getImageUrl();
            //         // 从 URL 中提取文件名
            //         String fileName = imagePath.substring(imagePath.lastIndexOf('/') + 1);
            //         File imageFile = new File(absoluteImagePath, fileName);
                    
            //         if (imageFile.exists()) {
            //             boolean deleted = imageFile.delete();
            //             if (deleted) {
            //                 logger.info("删除题目图片成功: " + imageFile.getAbsolutePath());
            //             } else {
            //                 logger.warning("删除题目图片失败: " + imageFile.getAbsolutePath());
            //             }
            //         }
            //     } catch (Exception e) {
            //         logger.warning("删除题目图片时出错: " + e.getMessage());
            //         // 继续执行，不因图片删除失败而中断整个删除操作
            //     }
            // }
            
            // 4. 删除题目记录
            int result = questionMapper.delete(id);
            if (result > 0) {
                logger.info("题目删除成功, ID: " + id);
                return Result.success("删除成功");
            } else {
                logger.warning("题目删除失败, ID: " + id);
                return Result.fail("删除失败");
            }
            
        } catch (Exception e) {
            // 检查是否为外键约束错误
            String errorMessage = e.getMessage() != null ? e.getMessage().toLowerCase() : "";
            if (errorMessage.contains("foreign key") || errorMessage.contains("constraint")) {
                logger.warning("删除题目失败: ID "+id+" 存在外键约束");
                return Result.fail("该题目已经关联到试题中，请先删除相关试卷");
            } else {
                logger.severe("删除题目时发生错误: " + e.getMessage());
                e.printStackTrace();
                return Result.fail("删除题目出错：" + e.getMessage());
            }
        }
    }

    /**
     * 获取教师发布的测试数据（基于result_name表的层次结构）
     * @param teacherId 教师ID
     * @return 按班级->测试名称组织的测试数据
     */
    @GetMapping("/publish/teacher")
    public Result getTeacherPublishedTests(@RequestParam String teacherId) {
        try {
            logger.info("获取教师发布的测试数据，教师ID: " + teacherId);
            
            // 首先获取该教师的所有班级
            List<Map<String, Object>> classes = jdbcTemplate.queryForList(
                "SELECT DISTINCT c.ClassId, c.ClassName FROM class c WHERE c.TeacherID = ?", 
                teacherId);
            
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (Map<String, Object> classData : classes) {
                Integer classId = ((Number) classData.get("ClassId")).intValue();
                String className = (String) classData.get("ClassName");
                
                // 获取该班级的所有测试发布记录
                String resultNameSql = "SELECT result_id, result_name, class_name FROM result_name WHERE class_name = ?";
                List<Map<String, Object>> publishedTests = jdbcTemplate.queryForList(resultNameSql, className);
                
                List<Map<String, Object>> testList = new ArrayList<>();
                
                for (Map<String, Object> testRecord : publishedTests) {
                    String resultIds = (String) testRecord.get("result_id");
                    String testName = (String) testRecord.get("result_name");
                    
                    if (resultIds != null && !resultIds.trim().isEmpty()) {
                        // 解析result_id字符串（逗号分隔）
                        String[] ids = resultIds.split(",");
                        
                        // 获取测试的基本信息（从第一个result记录获取）
                        String firstResultSql = "SELECT * FROM results WHERE id = ? LIMIT 1";
                        List<Map<String, Object>> firstResultList = jdbcTemplate.queryForList(firstResultSql, Integer.parseInt(ids[0].trim()));
                        
                        if (!firstResultList.isEmpty()) {
                            Map<String, Object> firstResult = firstResultList.get(0);
                            
                            // 获取所有相关的result记录和学生提交情况
                            String allResultsSql = "SELECT r.*, s.Name as studentName FROM results r " +
                                                 "LEFT JOIN student s ON r.student_id = s.StudentID " +
                                                 "WHERE r.id IN (" + resultIds + ") ORDER BY r.student_id";
                            List<Map<String, Object>> allResults = jdbcTemplate.queryForList(allResultsSql);
                            
                            // 统计提交情况
                            int totalStudents = allResults.size();
                            int submittedCount = 0;
                            int completedCount = 0;
                            double totalScore = 0.0;
                            int scoredCount = 0;
                            
                            for (Map<String, Object> result1 : allResults) {
                                String isSubmit = (String) result1.get("is_submit");
                                String isCorrect = (String) result1.get("is_correct");
                                Integer score = result1.get("score") != null ? ((Number) result1.get("score")).intValue() : null;
                                
                                if ("1".equals(isSubmit)) {
                                    submittedCount++;
                                }
                                if ("1".equals(isCorrect)) {
                                    completedCount++;
                                    if (score != null) {
                                        totalScore += score;
                                        scoredCount++;
                                    }
                                }
                            }
                            
                            // 构建测试信息
                            Map<String, Object> testInfo = new HashMap<>();
                            testInfo.put("testName", testName);
                            testInfo.put("resultIds", resultIds);
                            testInfo.put("startTime", firstResult.get("start_time"));
                            testInfo.put("endTime", firstResult.get("end_time"));
                            testInfo.put("answerTime", firstResult.get("answer_time"));
                            testInfo.put("purpose", firstResult.get("purpose"));
                            testInfo.put("totalStudents", totalStudents);
                            testInfo.put("submittedCount", submittedCount);
                            testInfo.put("completedCount", completedCount);
                            testInfo.put("averageScore", scoredCount > 0 ? totalScore / scoredCount : 0);
                            testInfo.put("submissionRate", totalStudents > 0 ? (double)submittedCount / totalStudents * 100 : 0);
                            testInfo.put("completionRate", totalStudents > 0 ? (double)completedCount / totalStudents * 100 : 0);
                            testInfo.put("studentDetails", allResults);
                            
                            // 判断测试状态
                            Timestamp endTime = (Timestamp) firstResult.get("end_time");
                            boolean isExpired = endTime != null && endTime.before(new Timestamp(System.currentTimeMillis()));
                            testInfo.put("isExpired", isExpired);
                            testInfo.put("status", isExpired ? "completed" : "pending");
                            
                            testList.add(testInfo);
                        }
                    }
                }
                
                // 构建班级信息
                Map<String, Object> classInfo = new HashMap<>();
                classInfo.put("classId", classId);
                classInfo.put("className", className);
                classInfo.put("tests", testList);
                
                result.add(classInfo);
            }
            
            logger.info("成功获取教师发布的测试数据，共 " + result.size() + " 个班级");
            return Result.success(result);
            
        } catch (Exception e) {
            logger.severe("获取教师发布的测试数据失败: " + e.getMessage());
            e.printStackTrace();
            return Result.fail("获取测试数据失败: " + e.getMessage());
        }
    }
}